<?php
/**
 * Created by paperphp
 * User: 22071
 * Date: 2019/6/25
 * Email: <zhendongdong@foxmail.com>
 */


use paper\App;
use paper\exception\ResponseException;
use paper\Url;


/**
 * @param $str
 * @param string $separator
 * @return string
 */
function toCamelCase($str, $separator = '_')
{
    $str = $separator . str_replace($separator, " ", strtolower($str));
    return ltrim(str_replace(" ", "", ucwords($str)), $separator);
}

/**
 * @param $camelCaps
 * @param string $separator
 * @return string
 */
function toUnderScore($camelCaps, $separator = '_')
{
    return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
}

/**
 * @param $str
 * @return string
 */
function filter($str)
{
    return htmlspecialchars($str, ENT_QUOTES);
}

/**
 * 快速生成url
 * @param string $uri 设置地址
 * @param array $params 设置参数
 * @return Url|string
 */

function url($uri = null, $params = null)
{
    $url = app()->url;
    return $url->path($uri, $params);
}

/**
 * 快速获取容器类
 * @return App|\paper\Container
 */
function app()
{
    return App::getInstance();
}

/**
 * 快速调用Request类
 * @return \paper\Request|null
 */
function request()
{
    return App::getInstance()->request;
}

/**
 * session辅助函数
 * @param string $key 要操作的session键名
 * @param mixed $value 要设置的值
 * @return mixed|void
 */
function session($key, $value = null)
{
    $session = app()->session;
    if ($value !== null) {
        $session->set($key, $value);
    } else {
        return $session->get($key);
    }
}

/**
 * cookie辅助函数
 * @param $key
 * @param null $value
 * @return mixed|void
 */
function cookie($key, $value = null)
{
    $cookie = app()->cookie;
    if ($value !== null) {
        $cookie->set($key, $value);
    } else {
        return $cookie->get($key);
    }
}

function config($source, $key)
{
    return app()->config->get($source, $key);
}

/**
 * 数组过滤
 * @param $key
 * @param $array
 * @return array|bool|mixed
 */
function array_column_filter($key, $array)
{
    if (is_string($key)) {
        return $array[$key] ?? false;
    }
    $data = [];
    foreach ($key as $item) {
        if (isset($array[$item])) {
            $data[$item] = $array[$item];
        }
    }
    return $data;
}

/**
 * 快速实例化模型
 * @param string $class 模型名称
 * @return mixed
 */
function model($class)
{
    return new $class();
}

/**
 * header location跳转辅助函数
 * @param string $url 要跳转的地址
 * @param int $code 设置301或者302跳转
 * @throws ResponseException
 */
function redirect($url = '', $code = 302)
{
    $response          = Response::create($url, $code, 'redirect', []);
    $responseException = new ResponseException();
    $responseException->setResponse($response);
    throw $responseException;
}


function dump($var)
{
    echo "<pre>";
    var_dump($var);
    echo "</pre>";
}